﻿using System;
using BLL;
using System.Text;
using System.Data;
using System.IO;
using System.Drawing;
using System.Drawing.Text;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using Ysb.Components;
using Aspose.Pdf;
using Aspose.Pdf.Kit;

using System.Threading;
public partial class Admin_ToExcelYueJie : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            //Tools.OpenWindow(this, Request.Url.AbsoluteUri);
            //return;
            //  ToExcel.ToExcelMotht(Request.QueryString["year"].ToString(), Request.QueryString["yue"].ToString(), Request.QueryString["userid"].ToString());
            //月结
            CreetImage();
        }
    }

    private System.Drawing.Bitmap bitmap;
    private string url;
    private int w = 1024, h = 1800;
    public void setBitmap()
    {


        using (WebBrowser wb = new WebBrowser())
        {
            wb.Width = w;
            wb.Height = h;
            wb.ScrollBarsEnabled = false;
            wb.Navigate(url);
            //确保页面被解析完全
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            }
            bitmap = new System.Drawing.Bitmap(w, h);
            wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, w, h));
            wb.Dispose();
        }
    }
    void CreetImage()
    {
        DataTable NameDT = new PublicSqlService().GetData("TrueName,AccountNo", "TblUserInfo", "uid=" + Request.QueryString["userid"].ToString());
        if (NameDT.Rows.Count != 1)
        {

            return;
        }

        int l = Request.Url.ToString().Trim().LastIndexOf("/");
        string ur = Request.Url.ToString().Trim().Substring(0, l);
        url = ur + "/UserPayList.asp?id=" + Request.QueryString["userid"].ToString() + "&ano=" + NameDT.Rows[0]["AccountNo"].ToString() + "&name=" + NameDT.Rows[0]["TrueName"].ToString() + "&year=" + Request.QueryString["year"].ToString() + "&yue=" + Request.QueryString["yue"].ToString();

        Thread thread = new Thread(new ThreadStart(setBitmap));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();

        while (thread.IsAlive)
            Thread.Sleep(100);
        ToPDF();
        //  bitmap.Save(Server.MapPath("a.bmp"));
    }
    void ToPDF()
    {
        iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 9, 18, 36, 36);//左右上下
        MemoryStream ms = new MemoryStream();
        try
        {
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            writer.CloseStream = false;
            doc.Open();
            System.Drawing.Image image = bitmap;
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.ScalePercent(50);//560 630
            doc.Add(img);
   

            image.Dispose();


        }
        catch (Exception err)
        {
            throw new Exception(err.Message);
        }
        finally
        {
            doc.Close();
            using (FileStream fs = new FileStream(Server.MapPath("out.pdf"), FileMode.Create))
            {
                ms.Position = 0;
                byte[] bit = new byte[ms.Length];
                ms.Read(bit, 0, (int)ms.Length);
                fs.Write(bit, 0, bit.Length);
            }
            ViewPdf(ms);
        }
    }
    private void ViewPdf(Stream fs)
    {
        Response.Clear();
        //中文名的话
        //Response.AppendHeader("Content-Disposition", "attachment;filename=" +
        //             HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
        Response.AddHeader("Content-Disposition", "attachment;FileName=Bill.pdf");
        Response.AddHeader("Content-Length", fs.Length.ToString());
        Response.ContentType = "application/pdf";
        long fileLength = fs.Length;
        int size = 10240;//10K一--分块下载，10K为1块
        byte[] readData = new byte[size];
        if (size > fileLength)
            size = Convert.ToInt32(fileLength);
        long fPos = 0;
        bool isEnd = false;
        while (!isEnd)
        {
            if ((fPos + size) >= fileLength)
            {
                size = Convert.ToInt32(fileLength - fPos);
                isEnd = true;
            }
            readData = new byte[size];
            fs.Position = fPos;
            fs.Read(readData, 0, size);
            Response.BinaryWrite(readData);
            Response.OutputStream.Flush();
            fPos += size;
        }
        fs.Close();
        Response.OutputStream.Close();
        Response.End();//非常重要，没有这句的话，页面的HTML代码将会保存到文件中
        Response.Close();
    }
}
